package cn.broadmax.boot.modules.sys.controller;

import cn.broadmax.boot.base.SuperController;
import cn.broadmax.boot.modules.sys.bean.log.SysLogPageSearch;
import cn.broadmax.boot.base.message.SResult;
import cn.broadmax.boot.modules.sys.entity.SysLog;
import cn.broadmax.boot.modules.sys.mapper.SysLogMapper;
import cn.broadmax.boot.modules.sys.service.ISysLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jexx.poi.ExcelWriter;
import jexx.poi.SheetWriter;
import jexx.poi.header.Headers;
import jexx.util.Console;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 日志
 * </p>
 */
@Api(tags = "日志")
@RestController
@RequestMapping("/sys/log")
@RequiredArgsConstructor
public class SysLogController extends SuperController {

    @Autowired
    private final ISysLogService sysLogService;

    @Autowired
    private final SysLogMapper sysLogMapper;

    @ApiOperation("分页查询日志")
    @GetMapping(value = "")
    public SResult<IPage<SysLog>> pageLogs(SysLogPageSearch search){
        LambdaQueryWrapper<SysLog> wrapper = SysLogPageSearch.createWrap(search);
        IPage<SysLog> page = sysLogService.page(getPage(), wrapper);
        return SResult.ok("", page);
    }

    @ApiOperation("导出日志")
    @GetMapping(value = "/export")
    public void exportLogs(SysLogPageSearch search, HttpServletResponse response){
        LambdaQueryWrapper<SysLog> wrapper = SysLogPageSearch.createWrap(search);
        List<SysLog> logs = sysLogService.list(wrapper);

        Headers headers = new Headers();
        headers.addHeader("username", "用户名");
        headers.addHeader("ip", "ip");
        headers.addHeader("logTime", "操作时间");
        headers.addHeader("logContent", "描述");

        ExcelWriter excelWriter = new ExcelWriter();
        SheetWriter sheetWriter = excelWriter.sheet();
        sheetWriter.writeHeader(headers);
        sheetWriter.writeRows(logs, headers);
        download("系统日志.xlsx", excelWriter, response);
    }

}
